<?php

namespace App\Models;

use App\Facade\Code;
use App\Utils\Output;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Throwable;

/**
 * 基础模型
 * Class BaseModel
 * @method $this find(int $id, array $columns = ['*']) static 获取对象
 * @method static $this create(array $array)
 * @package App
 */
class BaseModel extends Model
{
    use SoftDeletes;
    protected $hidden = ['deleted_at'];


    /**
     * 删除
     * @param array|int $id
     * @return Output|int
     * @throws Throwable
     */
    static function destroy($id)
    {
        $entity = static::find($id);
        if ($entity) {
            $entity->delete();
            return Output::success(__('common.tips.operation_successful'));
        }
        return Output::fail(__('common.tips.data_does_not_exist'));
    }

    /**
     * 存储
     * @param $data
     * @param int $id
     * @return Output
     */
    static function store($data, $id = 0)
    {
        if ($id) {
            $entity = static::find($id);
            if (empty($entity)) {
                return Output::fail(__('common.tips.data_does_not_exist'));
            }
            $entity->fill($data);
        } else {
            $entity = static::create($data);
        }
        $entity->save();
        return Output::success(__('common.tips.operation_successful'), $entity['id']);
    }


    protected function getCode($code, $value = false)
    {
        if (empty($value)) return '';
        return Code::get($code, $value);
    }

    /**
     * Prepare a date for array / JSON serialization.
     *
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
